import store from '@/store'
import { Result } from '@/types/http'
import axios from 'axios'
import { Toast } from 'antd-mobile'
import type { AxiosRequestConfig } from 'axios'
import history from './history'
import { refreshTokenAsync } from '@/store/slice/login'
import { logoutAsync } from '@/store/slice/profile'

const instance = axios.create({
  baseURL: 'https://toutiao.itheima.net/v1_0',
  timeout: 5000
})

// 请求拦截器
instance.interceptors.request.use(config => {
  const { login: {
    token
  } } = store.getState()
  if (token) {
    if (!config.url!.startsWith('/authorizations')) {
      config.headers.Authorization = `Bearer ${token}`
    }
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
instance.interceptors.response.use(null, async error => {
  if (!error.response) {
    Toast.show({
      content: '网络繁忙,请稍后重试',
      duration: 1500
    })
  } else if (error.response.status === 401) {
    // token过期
    try {
      // 拿到refresh_token
      const { login: { refresh_token } } = store.getState()
      // refresh_token不存在，抛出错误,走catch代码块,重新登录
      if (!refresh_token) {
        throw new Error(error)
      }
      // 获取新token
      await store.dispatch(refreshTokenAsync(refresh_token)).unwrap()
      // 继续发起请
      return request(error.config)
    } catch (e) {
      // refresh_token过期

      // 重新登录
      Toast.show({
        content: '登录过期,请重新登录',
        duration: 1500,
        afterClose: () => {
          // 清空用户信息
          store.dispatch(logoutAsync())

          const loginRoutePath = '/login'
          // 当前路径不是登录
          if (history.location.pathname !== loginRoutePath) {
            // 跳转至登录
            history.replace(loginRoutePath, {
              redirect: history.location.pathname
            })
          }
        }
      })

      return Promise.reject(e)
    }
  }
  return Promise.reject(error)
})

const request = <T>(config: AxiosRequestConfig) => {
  return instance.request<Result<T>>(config)
}

export default request



